//
// Created by 原帅 on 2021/2/16.
//

#include <fcntl.h>
#include <cstdio>
#include <unistd.h>
#include "IETaskInputReader.h"
#include <linux/input.h>
#include <string>
#include "errno.h"
#include "string.h"

IETaskInputReader::IETaskInputReader() {
    std::string inputDevice = "/dev/input/event2";
    fd = open(inputDevice.c_str(),O_RDONLY | O_NONBLOCK);
    if (fd<0) {
        printf("{IETaskInputReader}[%s] open %s failed : %d; error:%s\n",__func__ ,inputDevice.c_str(),fd,strerror(errno));
    } else {
        printf("{IETaskInputReader}[%s] open %s susceed : %d\n",__func__ ,inputDevice.c_str(),fd);
    }
    sampleFreq = 1000*100;
    gettimeofday(&lastSample, nullptr);
}

IETaskInputReader::~IETaskInputReader() {
    if (fd>0){
        close(fd);
    }
}

void IETaskInputReader::runloopTask(void *arg) {
    if (fd>0) {
        struct timeval currentTime = {0};
        gettimeofday(&currentTime, nullptr);
        unsigned long passedTime = (currentTime.tv_sec - lastSample.tv_sec) * 1000000 + (currentTime.tv_usec - lastSample.tv_usec);

        struct input_event event_mouse ={0};
        int ret = read(fd, &event_mouse, sizeof(event_mouse));
        if (ret>0){
            printf("{IETaskInputReader}[%s]: ret:%d ;event type:0x%x code:0x%x value:0x%x\n",
                   __func__ ,
                   ret,
                   event_mouse.type,
                   event_mouse.code,
                   event_mouse.value);
        }
        if (passedTime >= sampleFreq) {
            lastSample = currentTime;

        } else {
            return;
        }
    }
}